package cn.klaw.excel.handle;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.klaw.excel.ExcelHelper;
import cn.klaw.excel.ExcelPostHandle;
import cn.klaw.model.ExcelColumnAttr;
import cn.klaw.util.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * excel必填字段的字体颜色修改为红色
 */
public class ExcelRequireRedColor implements ExcelPostHandle {
    Map<String, ExcelColumnAttr> modelMap;
    Workbook workbook;

    @Override
    public void execute(ExcelHelper data, Map<String, Object> params) {
        ExportParams exportParams = data.getExportParams();
        workbook = data.getWorkbook();
        modelMap = data.getModelMap() != null ? data.getModelMap() : new HashMap<>();
        Sheet sheet = workbook.getSheet(exportParams.getSheetName());
        int rowLen = data.isComplexTable() ? 2 : 1;
        for (int i = 0; i < rowLen; i++) {
            Row headerRow = sheet.getRow(i);
            int lastCellNum = headerRow.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                Cell cell = headerRow.getCell(j);
                judgeRequired(cell);
            }
        }
    }

    private void judgeRequired(Cell cell) {
        if (cell == null) return;
        String key = ((XSSFCell) cell).getRichStringCellValue().getString();
        if (StringUtils.isNotBlank(key)) {
            String id = ExcelUtil.getIdFromCellValue(key);
            ExcelColumnAttr model = modelMap.get(id);
            if (Objects.isNull(model)) return;
            if (model.isRequire()) {
                ((XSSFCell) cell).getRichStringCellValue().setString("*" + key);
                CellStyle originalCellStyle = cell.getCellStyle();
                Font font = workbook.createFont();
                font.setColor(model.getFontColor());
                font.setBold(true);
                CellStyle redCellStyle = workbook.createCellStyle();
                redCellStyle.cloneStyleFrom(originalCellStyle); // 复制原有样式避免覆盖其他设置
                redCellStyle.setFont(font);
                cell.setCellStyle(redCellStyle);
            }
        }
    }
}
